/**
 * DocumentLoading 组件 - 显示文档生成过程的加载状态和进度
 * 
 * 该组件展示文档生成的三个主要步骤：
 * 1. 分析仓库结构
 * 2. 映射组件关系
 * 3. 生成详细文档
 * 
 * 包含进度条和每个步骤的实时更新内容预览，帮助用户了解
 * 文档生成的进度和中间结果。同时显示预估的生成成本。
 */
"use client";

import { DocumentStreamState } from "~/hooks/useDocument";
import { useLanguage } from "~/lib/LanguageContext";
import { useEffect, useRef } from "react";

type DocumentLoadingProps = {
  cost: string;
  status: DocumentStreamState["status"];
  explanation?: string;
  mapping?: string;
  document?: string;
};

export default function DocumentLoading({
  cost,
  status,
  explanation,
  mapping,
  document,
}: DocumentLoadingProps) {
  const { t } = useLanguage();
  const scrollRef = useRef<HTMLDivElement>(null);

  /**
   * 计算当前文档生成的整体进度百分比
   * 根据当前状态和各步骤的完成情况动态计算进度值
   */
  const getProgress = () => {
    const hasExplanation = !!explanation;
    const hasMapping = !!mapping;
    const hasDocument = !!document;
    
    if (status === "started") return 5;
    
    if (status === "explanation" || status === "explanation_chunk") {
      return hasExplanation ? 30 : 15;
    }
    
    if (status === "mapping" || status === "mapping_chunk") {
      return hasMapping ? 60 : 45;
    }
    
    if (status === "document" || status === "document_chunk") {
      return hasDocument ? 90 : 75;
    }
    
    if (status === "complete") return 100;
    
    return 0;
  };

  /**
   * 根据当前状态获取显示的进度消息
   */
  const getMessage = () => {
    if (status === "started") return t("documentLoading");
    if (status === "explanation" || status === "explanation_chunk")
      return "Step 1/3: Analyzing repository structure...";
    if (status === "mapping" || status === "mapping_chunk")
      return "Step 2/3: Mapping components...";
    if (status === "document" || status === "document_chunk")
      return "Step 3/3: Generating detailed document...";
    if (status === "complete") return "Document generation complete!";
    return t("documentLoading");
  };
  
  /**
   * 获取当前处于哪个步骤(1-3)
   */
  const getStepNumber = () => {
    if (status === "explanation" || status === "explanation_chunk") return 1;
    if (status === "mapping" || status === "mapping_chunk") return 2;
    if (status === "document" || status === "document_chunk" || status === "complete") return 3;
    return status === "started" ? 1 : 0;
  };

  // Auto-scroll effect
  useEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, [explanation, mapping, document]);

  // 当前进度
  const progress = getProgress();
  const stepNumber = getStepNumber();

  return (
    <div className="mx-auto w-full max-w-4xl p-4">
      <div className="overflow-hidden rounded-xl border-2 border-blue-200 bg-blue-50/30 backdrop-blur-sm">
        <div className="border-b border-blue-100 bg-blue-100/50 px-6 py-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <span className="text-sm font-medium text-blue-500">
                {getMessage()}
              </span>
            </div>
            <div className="flex items-center gap-3 text-xs font-medium text-blue-500">
              {cost && <span>Estimated cost: {cost}</span>}
              <span className="rounded-full bg-blue-100 px-2 py-0.5">
                Step {stepNumber}/3
              </span>
              <div className="flex gap-1">
                {[1, 2, 3].map((step) => (
                  <div
                    key={step}
                    className={`h-1.5 w-1.5 rounded-full transition-colors duration-300 ${
                      step <= stepNumber ? "bg-blue-500" : "bg-blue-200"
                    }`}
                  />
                ))}
              </div>
            </div>
          </div>
        </div>

        {/* 进度条 */}
        <div className="h-1.5 w-full bg-blue-100">
          <div
            className="h-full bg-blue-500 transition-all duration-500 ease-in-out"
            style={{ width: `${progress}%` }}
          ></div>
        </div>

        {/* 滚动内容区域 */}
        <div ref={scrollRef} className="max-h-[400px] overflow-y-auto p-6">
          <div className="space-y-4">
            <div
              className={`rounded-lg border-[3px] border-black p-4 shadow-[4px_4px_0_0_#000000] transition-colors dark:border-gray-700 dark:shadow-[4px_4px_0_0_#1f1f1f] ${
                status === "explanation" ||
                status === "explanation_chunk" ||
                status === "mapping" ||
                status === "mapping_chunk" ||
                status === "document" ||
                status === "document_chunk" ||
                status === "complete"
                  ? "bg-blue-100 dark:bg-blue-950"
                  : "bg-gray-100 dark:bg-gray-800"
              }`}
            >
              <h3 className="text-base font-semibold text-gray-900 dark:text-white">
                Step 1: Analyzing Repository Structure
              </h3>
              {explanation && (
                <div className="mt-2 max-h-48 overflow-y-auto text-sm text-gray-700 dark:text-gray-300">
                  <p className="whitespace-pre-wrap">{explanation}</p>
                </div>
              )}
            </div>

            <div
              className={`rounded-lg border-[3px] border-black p-4 shadow-[4px_4px_0_0_#000000] transition-colors dark:border-gray-700 dark:shadow-[4px_4px_0_0_#1f1f1f] ${
                status === "mapping" ||
                status === "mapping_chunk" ||
                status === "document" ||
                status === "document_chunk" ||
                status === "complete"
                  ? "bg-blue-100 dark:bg-blue-950"
                  : "bg-gray-100 dark:bg-gray-800"
              }`}
            >
              <h3 className="text-base font-semibold text-gray-900 dark:text-white">
                Step 2: Mapping Components
              </h3>
              {mapping && (
                <div className="mt-2 max-h-48 overflow-y-auto text-sm text-gray-700 dark:text-gray-300">
                  <p className="whitespace-pre-wrap">{mapping}</p>
                </div>
              )}
            </div>

            <div
              className={`rounded-lg border-[3px] border-black p-4 shadow-[4px_4px_0_0_#000000] transition-colors dark:border-gray-700 dark:shadow-[4px_4px_0_0_#1f1f1f] ${
                status === "document" ||
                status === "document_chunk" ||
                status === "complete"
                  ? "bg-blue-100 dark:bg-blue-950"
                  : "bg-gray-100 dark:bg-gray-800"
              }`}
            >
              <h3 className="text-base font-semibold text-gray-900 dark:text-white">
                Step 3: Generating Document
              </h3>
              {document && document.trim() !== "" && (
                <div className="mt-2 max-h-48 overflow-y-auto text-sm text-gray-700 dark:text-gray-300">
                  <p className="whitespace-pre-wrap">
                    {document}
                  </p>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
} 